package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.utils.Constants;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/role")
public class SysRoleController extends BaseController{
    private static final Logger LOGGER = LoggerFactory.getLogger(SysRoleController.class);

    @Resource
    private SysRoleService sysRoleService;

    @GetMapping("/list")
    public String list(Model  model) {
        try {
            List sysRoleList = sysRoleService.findAll();
            model.addAttribute("list", sysRoleList);
            return "role/list";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping("/save")
    public String toSave(SysRole sysRole) {
        return "role/save";
    }

    @PostMapping("/save")
    public String doSave(@ModelAttribute SysRole sysRole,Model model) {
//            通过父类的 session 方法获取登录用户，由于泛型自动转换无需强转
        SysUser loginUser = (SysUser) session(Constants.SESSION_USER);
        if (sysRole.getId() == null) {
//                如果是添加用户，关联创建用户为当前登录用户
            sysRole.setCreatedUserId(loginUser.getId());
        } else {
//                如果是修改用户，关联修改用户为当前登录用户
            sysRole.setUpdatedUserId(loginUser.getId());
        }
        try {
            boolean ok = sysRoleService.saveOrUPdate(sysRole);
            if (ok) {
                //保存成功 跳转到列表页面
                return redirect("/main/role/list");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return "role/save";
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        try {
            SysRole sysRole = sysRoleService.getById(id);
            model.addAttribute("sysRole", sysRole);
            return "role/save";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @ResponseBody
    @GetMapping("/codeExist")
    public String codeExist(@RequestParam("code") String code) {
        LOGGER.debug("检查编码 code={}的角色是否存在", code);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(code)) {
            resultMap.put("exist", 0);
        } else {
            try {
                SysRole sysRole = sysRoleService.findByCode(code);
                if (null != sysRole) {
//                    已经存在，设置为1
                    resultMap.put("exist", 1);
                } else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                LOGGER.error("SysRoleController 中的" + "codeExist方法执行出现错误。", e);
                resultMap.put("error", "出现异常，请联系管理员处理！");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @ResponseBody
    @DeleteMapping("/del/{id}")
    public Map<String, Object> delete(@PathVariable("id") Long id) {
        HashMap<String, Object> resultMap = new HashMap<>();
        try {
            int count = sysRoleService.delete(id);
            if (count > 0 && count <501) {
                resultMap.put("code", 200);
                resultMap.put("msg", "删除成功");
            }else if (count == 501) {
                resultMap.put("code", count);
                resultMap.put("msg", "删除失败，该角色下有员工");
            }else {
                resultMap.put("code", 500);
                resultMap.put("msg", "删除失败");
            }
        } catch (Exception e) {
            LOGGER.error("SysRoleController 中的 delete方法执行出现错误。", e);
            resultMap.put("code", 500);
            resultMap.put("msg", "删除时发生异常: " + e.getMessage());
        }
        return resultMap;
    }
}